package com.demo05.controller;

import com.alibaba.fastjson.JSON;
import com.demo05.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @RequestMapping("/j1")
    @ResponseBody //只要有这个注解，它就不会走视图解析器，会直接返回一个字符串
    public String json1() {

//        jackson里面有一个ObjectMapper可以生成json

        ObjectMapper mapper = new ObjectMapper();
        User user = new User("张波", 21, "男");

        String asString = null;
        try {
            asString = mapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return asString;
    }


    @RequestMapping("/j2")
    @ResponseBody
    public String json2() throws JsonProcessingException {

        User user1 = new User("张波1号", 21, "男");
        User user2 = new User("张波2号", 21, "男");
        User user3 = new User("张波3号", 21, "男");
        User user4 = new User("张波4号", 21, "男");
        User user5 = new User("张波5号", 21, "男");
        User user6 = new User("张波6号", 21, "男");

        List<User> userList = new ArrayList<>();

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        userList.add(user6);


        return JSON.toJSONString(userList);
    }


}
